/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package queenb.web.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Vector;

/**
 *
 * @author pham anh hao, vietquynh, thanhct
 */
public class TimeHelper {

    private static int hour;
    private static int minute;

    private static void setTime(int h, int m) {
        hour = h >= 0 && h < 24 ? h : 0; // validate hour
        if (hour == 0) {
            minute = 0;
        } else {
            minute = m >= 0 && m < 60 ? m : 0; // validate minute
        }
    }


    public static Timestamp toTimeStamp(String date, String time) throws ParseException {
        String dateTime = date.trim()+" "+TimeHelper.validateTime(time);
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        Date curentDate = sdf.parse(dateTime);
       return  new Timestamp(curentDate.getTime());
    }

    public static Timestamp toTimeStamp(String datetime) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        Date curentDate = sdf.parse(datetime);
       return  new Timestamp(curentDate.getTime());
    }

    // convert to String in universal-time format (HH:MM:SS)
    public static String toUniversalString() {
        return String.format("%02d:%02d", hour, minute);
    }

    // convert to String in standard-time format (H:MM:SS AM or PM)
    @Override
    public String toString() {
        return String.format("%d:%02d %s", (hour == 0 || hour == 12 ? 12 : hour % 12), minute,
                (hour < 12 ? "AM" : "PM"));
    }

    public static String validateTime(String strTime) throws IllegalArgumentException {
        String time = "";
        strTime = strTime.trim();
        strTime = strTime.replaceAll(":", "").replaceAll(" ", "");
        if (strTime.length() == 2 && strTime.length() > 0) {
            hour = Integer.parseInt(strTime.substring(0, 2));
            setTime(hour, 0);
            time = toUniversalString();
        }
        if (strTime.length() == 1 && strTime.length() > 0) {
            hour = Integer.parseInt(strTime.substring(0, 1));
            setTime(hour, 0);
            time = toUniversalString();
        } else if (strTime.length() == 3) {
            throw new IllegalArgumentException("Not right format! Try again");
        } else if (strTime.length() <= 4 && strTime.length() > 2) {
            hour = Integer.parseInt(strTime.substring(0, 2));
            minute = Integer.parseInt(strTime.substring(2, 4));
            setTime(hour, minute);
            time = toUniversalString();
        } else if (strTime.length() > 4) {
            throw new IllegalArgumentException("Not right format! Try again");
        }
        return time;
    }

    public static boolean compareTime(String val1, String val2) throws NumberFormatException {
        boolean result = true;
        if (Integer.parseInt(val2) < Integer.parseInt(val1)) {
            result = false;
        }
        return result;
    }

    public static String toDbTimeString(String localTime) {
        String dbTimeString = "";
        DateFormat currentTimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
        try {
            currentTimeFormat.setLenient(true);
            Date currentTime = currentTimeFormat.parse(localTime.toUpperCase());
            dbTimeString = currentTimeFormat.format(currentTime);
            Calendar calendar = java.util.GregorianCalendar.getInstance(Locale.getDefault());
            calendar.setTime(currentTime);
            int hours = calendar.get(Calendar.HOUR_OF_DAY);
            int minutes = calendar.get(Calendar.MINUTE);
            String strHours = hours < 10 ? "0" + hours : hours + "";
            String strMinutes = minutes < 10 ? "0" + minutes : minutes + "";
            dbTimeString = strHours + strMinutes;
            return dbTimeString;
        } catch (Exception e) {
            throw new IllegalArgumentException("TimeHelper.LocalTimeIsNotRightFormat");
        }
    }

    /**
     * convert a work block to from local time, ex: 08122345 to be 8:12 AM
     */
    public String getLocalTimeFrom(String workTimeBlock) throws IllegalArgumentException {
        String timeFrom = "";
        if (workTimeBlock == null || workTimeBlock.length() != 8) {
            throw new IllegalArgumentException("Work time block must be 8 digits");
        }
        timeFrom = toLocalTimeString(workTimeBlock.substring(0, 4));
        return timeFrom;
    }

    /**
     * convert a work block to from local time, ex: 08122345 to be 11:45 PM
     */
    public String getLocalTimeTo(String workTimeBlock) throws IllegalArgumentException {
        String timeTo = "";
        if (workTimeBlock == null || workTimeBlock.length() != 8) {
            throw new IllegalArgumentException("Work time block must be 8 digits");
        }
        timeTo = toLocalTimeString(workTimeBlock.substring(4, 8));
        return timeTo;
    }

    /**
     * method to parse  a db time to local time,ex: 2115 to 9:15 PM
     * @param dbTime
     * @return
     */
    private String toLocalTimeString(String dbTime) throws IllegalArgumentException {
        String localTimeString = null;
        dbTime = dbTime.trim();
        if (dbTime == null || dbTime.length() != 4) {
            throw new IllegalArgumentException("Db time is not in right format of hhmm, ex:'0830'");
        }
        int hours = Integer.parseInt(dbTime.substring(0, 2));
        int minutes = Integer.parseInt(dbTime.substring(2, 4));
        java.util.Calendar calendar = java.util.GregorianCalendar.getInstance(Locale.getDefault());
        calendar.set(2008, 1, 1, hours, minutes);
        Date date = calendar.getTime();
        DateFormat currentTimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
        localTimeString = currentTimeFormat.format(date);
        return localTimeString;
    }

    /**
     * from , to is not valid with the workblock
     * @param workBlock
     * @param from
     * @param to
     * @return
     */
    private boolean isValidTwoBlocks(String workBlock, String timedef) {

        //the workblock is in right format
        String strFrom = getLocalTimeFrom(workBlock);
        String strTo = getLocalTimeTo(workBlock);
        String strTimeDefFrom = getLocalTimeFrom(timedef);
        String strTimeDefTo = getLocalTimeTo(timedef);
        DateFormat currentTimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());

        try {
            currentTimeFormat.setLenient(true);
            //convert to date
            Date dateFrom = currentTimeFormat.parse(strFrom);
            Date dateTo = currentTimeFormat.parse(strTo);
            Date dateFrom1 = currentTimeFormat.parse(strTimeDefFrom);
            Date dateTo1 = currentTimeFormat.parse(strTimeDefTo);

            if (dateFrom.before(dateFrom1) && dateFrom1.before(dateTo) || dateFrom.before(dateTo1)
                    && dateTo1.before(dateTo) || dateFrom1.before(dateFrom) && dateFrom.before(dateTo1)
                    || dateFrom1.before(dateTo) && dateTo.before(dateTo1)) {
                return false;
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("TimeHelper.LocalTimeIsNotRightFormat");
        }
        return true;
    }

    public static boolean ispassDay(String from, String to) {
        DateFormat currentTimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
        try {
            currentTimeFormat.setLenient(true);
            //convert to date
            Date dateFrom = currentTimeFormat.parse(from);
            Date dateTo = currentTimeFormat.parse(to);
            if (dateTo.before(dateFrom)) {
                return true;
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("TimeHelper.LocalTimeIsNotRightFormat");

        }
        return false;
    }

    public static Vector<String> get24HoursInLocalFormat() {
        Vector<String> hourIndayList = new Vector<String>();
        DateFormat currentTimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        //String s = Locale.getDefault().getCountry();
        for (int i = 0; i < 24; i++) {
            calendar.set(Calendar.HOUR_OF_DAY, i);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            hourIndayList.addElement(currentTimeFormat.format(calendar.getTime()));
        }
        return hourIndayList;
    }

    public static Date toLocalDate(String date) throws Exception {
        Date dateFormat = null;
        DateFormat currentTimeFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
        try {
            currentTimeFormat.setLenient(true);
            dateFormat = currentTimeFormat.parse(date);
        } catch (Exception err) {
            throw new Exception("Can not format to date. Please check again.");
        }
        return dateFormat;
    }

    public static String toLocalDateString(Date date) {
        String formatString = "";
        DateFormat currentTimeFormat = DateFormat.getDateInstance(DateFormat.LONG, Locale.getDefault());
        currentTimeFormat.setLenient(true);
        formatString = currentTimeFormat.format(date);
        return formatString;
    }

    /**
     * from and to is not valid to current timedef
     */
    public boolean isValidWorkBlock(String timeDef, String timedef, int editingBlockIndex) {
        String[] workBlocks = getWorkBlocks(timeDef);
        for (int index = 0; index < workBlocks.length; index++) {
            String workBlock = workBlocks[index];
            if (editingBlockIndex != index) {
                if (!isValidTwoBlocks(workBlock, timedef)) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * check if two dates are equal in year, day, year
     */
    public boolean isEqualDate(Date date1, Date date2) {
        Calendar calendar1 = Calendar.getInstance(Locale.getDefault());
        Calendar calendar2 = Calendar.getInstance(Locale.getDefault());
        calendar1.setTime(date1);
        calendar2.setTime(date2);
        return calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH)
                && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH)
                && calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
    }

    public static String getTimeDefFromStrArray(String[] array) {
        String value = "";
        for (String s : array) {
            value = value + s;
        }
        return value.trim();
    }

    public String[] getWorkBlocks(String timeDef) {
        int workBlockNum = timeDef.length() / 8;
        String[] workBlocks = new String[workBlockNum];

        for (int i = 0, j = 0; i < workBlockNum; i++, j = j + 8) {
            workBlocks[i] = timeDef.substring(j, j + 8);
        }
        return workBlocks;
    }

    public static void main(String arg[]) throws ParseException {
        System.out.println(TimeHelper.validateTime("1230"));
        System.out.println(TimeHelper.toTimeStamp("12/12/2009","12:12").toString());
        System.out.println(TimeHelper.toTimeStamp("12/12/2009","1230"));

    }
}
